package database

import (
	"database/sql"
	l "log"
	"time"

	"gorm.io/gorm"
	gl "gorm.io/gorm/logger"

	log "gitee.com/chenhonghua/ginorigin/log"
)

var (
	connection *gorm.DB
	sqldb      *sql.DB
	c          DatabaseConfig
)

type Connect interface {
	GenConnect(gormConf *gorm.Config) (*gorm.DB, *sql.DB, error)
}

type DatabaseConfig struct {
	Enable               bool   `mapstructure:"enable" json:"enable" yaml:"enable"`                                                 // 是否开启
	EnableAutoMigrate    bool   `mapstructure:"enable-auto-migrate" json:"enableAutoMigrate" yaml:"enable-auto-migrate"`            // 是否开启自动生成数据库表
	EnableAutoImportData bool   `mapstructure:"enable-auto-import-data" json:"enableAutoImportData" yaml:"enable-auto-import-data"` // 是否开启自动导入数据
	LogMode              string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"`                                            // 日志模式

	DBConfig Connect `mapstructure:"-" json:"-" yaml:"-"` // 数据库配置
}

func (dbc DatabaseConfig) Load() {
	c = dbc
	if !dbc.Enable || connection != nil {
		return
	}
	log.Debugf("数据库模块:%v\n", c)
	ormConfig := &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	}
	_default := gl.New(l.New(log.DefaultLogger.Out, "\r\n", l.LstdFlags), gl.Config{
		SlowThreshold: 200 * time.Millisecond,
		LogLevel:      gl.Warn,
		Colorful:      true,
	})
	switch c.LogMode {
	case "silent", "Silent":
		ormConfig.Logger = _default.LogMode(gl.Silent)
	case "error", "Error":
		ormConfig.Logger = _default.LogMode(gl.Error)
	case "warn", "Warn":
		ormConfig.Logger = _default.LogMode(gl.Warn)
	case "info", "Info":
		ormConfig.Logger = _default.LogMode(gl.Info)
	default:
		ormConfig.Logger = _default.LogMode(gl.Info)
	}
	conn, sql, e := c.DBConfig.GenConnect(ormConfig)
	if e != nil {
		log.Fatal(e)
	}
	connection = conn
	sqldb = sql
}
